package com.xunwulian.web.controller.buss;

import com.alibaba.dubbo.config.annotation.Reference;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.xunwulian.api.iface.UserAPI;
import com.xunwulian.base.constant.ConstantBean;
import com.xunwulian.base.entity.BillEntity;
import com.xunwulian.base.entity.Page;
import com.xunwulian.base.entity.User;
import com.xunwulian.base.util.DateStyle;
import com.xunwulian.base.util.PageData;
import com.xunwulian.web.controller.BaseController;
import com.xunwulian.web.entity.BillEntityWrapper;
import com.xunwulian.web.innerservice.InnerBillService;
import com.xunwulian.web.util.Const;
import org.apache.http.client.utils.DateUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "/bill")
public class BillController extends BaseController {

    String menuUrl = "bill/list.do"; // 菜单地址(权限用)

    @Reference
    private UserAPI userAPI;

    @Autowired
    private InnerBillService billService;

    private Gson gson = new GsonBuilder().setPrettyPrinting().create();

    /**
     * 列表
     *
     * @param page
     * @return
     */
    @RequestMapping(value = "/list")
    public ModelAndView list(@Param("page") Page page) {

        logBefore(logger, "列表");

        logger.info("page:" + gson.toJson(page));

        ModelAndView mv = this.getModelAndView();
        PageData pd = this.getPageData();
        String owner = pd.get("owner") != null ? (String) pd.get("owner") : "";
        String searchKey = pd.get("searchKey") != null ? (String) pd.get("searchKey") : "";

        // 从session获取用户信息
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        List<BillEntity> varList = billService.getBillList(user.getROLE_ID(),
                user.getUSER_ID(),
                user.getAppId(),
                owner,
                searchKey,
                page);

        List<BillEntityWrapper> listWrapper = new ArrayList<>();

        if (varList != null && varList.size() > 0) {
            listWrapper = varList.stream().map(p -> new BillEntityWrapper(p)).collect(Collectors.toList());
        }

        mv.addObject("varList", listWrapper);

        mv.setViewName("system/bill/bill_list");

        mv.addObject("owner", owner);
        mv.addObject("searchKey", searchKey);
        mv.addObject("page", page);
        mv.addObject(Const.SESSION_QX, this.getHC()); // 按钮权限

        return mv;
    }

    /**
     * 生成账单
     */
//    @Transactional
    @RequestMapping(value = "/generate")
    public void generate() {

        Page page = new Page();
        page.setCurrentPage(1);
        page.setShowCount(10000);

        List<User> list = userAPI.listPage(page,
                null,
                null,
                ConstantBean.ADMIN_USER_ID).getData();

        String month = DateUtils.formatDate(new Date(), DateStyle.YYYY_MM.getValue());

        logger.info("生成账单：" + gson.toJson(list));
        list.forEach(p -> billService.generateByUserId(month, p.getUSER_ID()));

    }


    /**
     * @return
     */
    public Map<String, String> getHC() {
        Subject currentUser = SecurityUtils.getSubject(); // shiro管理的session
        Session session = currentUser.getSession();
        return (Map<String, String>) session.getAttribute(Const.SESSION_QX);
    }


    /**
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(format,
                true));
    }

}
